package com.example.admin.controller.sys;

import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.admin.entity.SysUser;
import com.example.admin.service.ISysUserService;
import com.example.util.APIState;
import com.example.util.AjaxResult;
import com.example.util.EntityUtil;
import com.example.util.Pager;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wangkai
 * @since 2019-06-04
 */
@RestController
@RequestMapping("/sys/sysUser")
public class SysUserController {

	@Resource(name = "sysUserService")
	private ISysUserService service;

	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/page")
	public AjaxResult page(Pager pf) {
		Page<SysUser> page = new Page<>();
		page.setCurrent(pf.getPage());
		page.setSize(pf.getLimit());
		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
		Pager<SysUser> pager = new Pager<SysUser>(service.page(page, queryWrapper));
		pager.setRows(pager.getRows().stream().map(user -> (SysUser) EntityUtil.formateEntity(user))
				.collect(Collectors.toList()));
		return new AjaxResult(APIState.S00, pager);
	}

	/**
	 * 保存
	 * 
	 * @param sysUser
	 * @return
	 */
	@RequestMapping(value = "/save")
	public AjaxResult save(SysUser sysUser) {
		if (sysUser != null) {
			if (service.saveSysUser(sysUser)) {
				return new AjaxResult(APIState.S00, "保存成功");
			}
		}
		return new AjaxResult(APIState.S01, "保存失败");
	}

	/**
	 * 修改
	 * 
	 * @param sysUser
	 * @return
	 */
	@RequestMapping(value = "/update")
	public AjaxResult update(SysUser sysUser) {
		if (sysUser != null) {
			if (service.updateSysUser(sysUser)) {
				return new AjaxResult(APIState.S00, "保存成功");
			}
		}
		return new AjaxResult(APIState.S01, "保存失败");
	}

	/**
	 * 刪除
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}/delete")
	public AjaxResult delete(@PathVariable Integer id) {
		if (id != null) {
			SysUser sysUser = service.getById(id);
			if (sysUser != null) {
				if (service.deleteSysUser(sysUser)) {
					return new AjaxResult(APIState.S00, "删除成功");
				}
			} else {
				return new AjaxResult(APIState.S01, "当前用户不存在请重新刷新列表");
			}
		}
		return new AjaxResult(APIState.S01, "删除失败");
	}
}
